#!/usr/bin/env python
# Author: Chris Moyer
# Upload static files to the static S3
# bucket. This script also will
# make all of these files public
import os, os.path
import sys

def upload_dir(dir_name, bucket, prefix="static"):
	"""
	Upload this directory to S3

	@param dir_name: directory to upload
	
	@param bucket: the bucket to upload to
	@type bucket: boto.s3.bucket

	@param prefix: The prefix to remove from the key in S3
	"""
	for item in os.listdir(dir_name):
		if not item[0] == ".":
			f_name = os.path.join(dir_name, item)
			if os.path.isdir(f_name):
				upload_dir(f_name, bucket, prefix)
			else:
				upload_file(f_name, bucket, prefix)

def upload_file(f_name, bucket, prefix="static"):
	"""
	Upload this file directly to S3

	@param f_name: the name of the file (relative to cwd) to upload

	@param bucket: the bucket to upload to
	@type bucket: boto.s3.bucket

	@param prefix: the prefix to upload to
	"""
	k = bucket.new_key(f_name[len(prefix):].strip('/'))
	print k.name,
	sys.stdout.flush()
	k.set_contents_from_filename(f_name)
	k.make_public()
	print "................done"


if __name__ == "__main__":
	from optparse import OptionParser
	parser = OptionParser(version = "%prog version 1.0")
	parser.add_option("-c", "--config", help="Config File, extends app.yaml", dest="config_name", default=None)
	parser.add_option("-f", "--file", help="Specific file to upload", dest="file_name", default=None)
	parser.add_option("-b", "--bucket", help="S3 Bucket name to upload to", dest="bucket_name", default=None)
	(options, args) = parser.parse_args()
	if len(args) > 0:
		os.chdir(args[0])

	print "Loading Config...."
	import marajo
	marajo.set_env('.', None)
	if options.config_name:
		import yaml
		marajo.config.update(yaml.load(options.config_name))

	print "Connecting to S3...."
	import boto
	s3 = boto.connect_s3()
	if options.bucket_name:
		bucket = s3.get_bucket(options.bucket_name)
	else:
		bucket = s3.get_bucket(marajo.config.get("static_bucket"))

	print "Uploading to bucket: %s" % bucket.name
	if options.file_name:
		print "Uploading single file"
		upload_file(options.file_name, bucket)
	else:
		print "Uploading files"
		upload_dir("static", bucket)
